<style scoped>
.AllLayout {
    background-color: #d6d1d157;
}

.ContentTop {
    background-color: white;
    width: 68%;
    margin-left: 16%;
    padding-top: 7px;
    padding-bottom: 6px;
    border-bottom: 1px solid #a28c8c;
}

.ContentTop i {
    font-size: 35px;
}

.ContentBottom {
    background-color: white;
    margin-left: 16%;
    padding-top: 7px;
    width: 68%;
}

.authorPicture {
    width: 51px;
    height: 51px;
    border-radius: 36px;
}

.authMessage {
    margin-left: 16px;
}

.authMessage div:nth-child(1) {
    font-size: 19px;
    margin-top: 5px;
}

.authMessage div:nth-child(2) {
    font-size: 14px;
    color: #897f7f;
    margin-top: 3px;
}

h2 {
    margin: 12px 0 16px 2%;
}

.allContent {
    width: 96%;
    margin-left: 25px;
}

.ContentImg {
    display: flex;
}

.ContentImg img {
    width: 306px;
    margin-left: 25px;
    margin-top: 20px;
}

.CommentsArea {
    background-color: #fbf5f5;
    width: 93%;
    margin-left: 3%;
    margin-top: 16px;
  padding-bottom: 1px;
    border-radius: 12px;
}

.AreaTop {
    display: flex;
    margin-left: 25px;
    border-bottom: 1px solid #7c7474;
    padding-bottom: 7px;
    padding-top: 11px;
}

.AreaTop i {
    font-size: 19px;
    margin-left: 10px;
}

.AreaTop div {
    margin-left: 10px;
    line-height: 24px;
}

.CommentsAuthorPicture {
    width: 40px;
    border-radius: 36px;
    height: 40px;
}

.CommentsAuthMessage {
    margin-left: 16px;
}

.CommentsAuthMessage div:nth-child(1) {
    margin-top: 7px;
    font-size: 15px;
}

.CommentsAuthMessage div:nth-child(2) {
    font-size: 12px;
    margin-top: 5px;
    color: #756b6b;
}

.commentsTop {
    display: flex;
    margin-left: 20px;
    margin-top: 7px;
}

.commentsBottom {
    display: flex;
    margin-left: 6%;
    margin-top: 7px;
    /*margin-bottom: 12px;*/
    position: relative;
    padding-bottom: 15px;
}

.SecondComments {
    width: 90%;
    margin-left: 57px;
    background-color: #f9ebeb;
    border-radius: 21px;
}

.CommentsContent {
    font-size: 16px;
}

#CommentPraise {
    position: absolute;
    right: 165px;
    font-size: 17px;
    cursor: pointer;
}

#hasPraised {
    color: #c15353;
}

.PraiseNumber {
    position: absolute;
    right: 147px;
}

.controlReply {
    height: 29px;
    width: 96%;
    padding-top: 4px;
    border-bottom: 1px solid #bfb7b7;
    margin-left: 2%;
    position: relative;
}

.controlReply i {
    font-size: 30px;
    position: absolute;
    right: 36px;
    cursor: pointer;
}

.addCommentBox {
    margin-left: 20px;
    margin-top: 10px;
    margin-bottom: 40px;
}
.replyFirstComment{
  position: absolute;
  right: 95px;
  cursor: pointer;
}
#likeThisPassage{
  cursor: pointer;
}
</style>

<template>
    <div class="AllLayout">
        <div class="ContentTop">
            <i @click="backPage" class="iconfont icon-fanhui" id=""></i>
        </div>
        <div class="ContentBottom">
            <div style="padding-left: 21px;display: flex">
                <img class="authorPicture" :src="content.avatar">
                <div class="authMessage">
                    <div>{{ content.username }}</div>
                    <div>{{ content.createTime }}</div>
                </div>
            </div>
            <div>
                <h2>{{ content.title }}</h2>
                <div class="allContent">{{ content.content }}</div>
            </div>
            <div class="ContentImg">
                <img v-for="(item, index) in content.imageUrl ? content.imageUrl.split('||') : []" :key="index"
                    :src="item">
            </div>


            <div class="CommentsArea">
                <div class="AreaTop">
                    <i class="iconfont icon-fenxiang" id=""></i>
                    <div></div>
                    <i class="iconfont icon-pinglunxiao" id=""></i>
                    <div>{{ content.commentCount }}</div>
                    <i
                        :style="{ color: content.hasPraised === 'icon-dianzan' ? '#c15353' : undefined }"
                        :class="['iconfont', content.hasPraised]"
                       id="likeThisPassage"
                        @click="likeOrCancelLike"
                    ></i>
                    <div>{{ content.praise }}</div>
                </div>

                <!-- 发布评论区域 -->
                <div class="addCommentBox">
                    <h3>发布评论</h3>
                    <el-input v-model="commentText" style="width: 650px" :rows="2" type="textarea"
                        placeholder="请输入评论内容，ctrl+enter发送" @keydown="handleKeyDown" />
                    <el-button type="primary" style="margin-left:20px" @click="postComment">发布</el-button>
                </div>
                <div>
                    <div v-for="(item, index) in comments">
                        <div class="commentsTop">
                            <img class="CommentsAuthorPicture" :src="item.user.avatar">
                            <div class="CommentsAuthMessage">
                                <div>{{ item.user.username }}</div>
                                <div>{{ item.createTime }}</div>
                            </div>
                        </div>
                        <!-- 一级评论底部操作按钮 -->
                        <div class="commentsBottom">
                            <div class="CommentsContent">{{ item.content }}</div>
                            <i :class="['iconfont', item.hasPraise]"
                                :style="{ color: item.hasPraise === 'icon-dianzan' ? '#c15353' : '' }"
                                id="CommentPraise" @click="likeFirstComment(index)"></i>
                            <div class="PraiseNumber">{{ item.likes }}</div>
                          <div class="replyFirstComment" style="cursor: pointer" @click="controlOpenFirstCommentArea(index)">回复</div>
                        </div>
                        <ReplyFirstComment
                            v-if="controlOpenFirstComment===index"
                            :fatherCommentMessage="{uid: item.id,forumId:forumId,FirstCommentId:item.id}"
                            @message-sent="handleMessage"
                        />
                        <!-- 二级评论区域 -->
                        <div class="SecondComments">
                            <div class="controlReply">
                                <i @click="ShowReplyArea(index)" :class="['iconfont', item.ControlReply]" id=""></i>
                            </div>
                            <div v-if="item.isShowReply">
                                <div v-for="(child, childIndex) in item.reply">
                                    <div style="padding-bottom: 28px;">
                                        <div class="commentsTop">
                                            <img class="CommentsAuthorPicture" :src="child.user.avatar">
                                            <div class="CommentsAuthMessage">
                                                <div>{{ child.user.username }}</div>
                                                <div>{{ child.createTime }}</div>
                                            </div>
                                        </div>
                                        <div class="commentsBottom">
                                            <div class="CommentsContent">{{ child.content }}</div>
                                            <i :class="['iconfont', child.hasPraise]"
                                                :style="{ color: child.hasPraise === 'icon-dianzan' ? '#c15353' : undefined }"
                                                id="CommentPraise" @click="likeSecondComment(index, childIndex)"></i>
                                            <div class="PraiseNumber">{{ child.likes }}</div>
                                          <div class="replyFirstComment" @click="replySecondComment(child.id)">回复</div>
                                        </div>
                                      <div v-if="controlOpenSecondComment===child.id" style="padding-bottom: 12px">
                                        <ReplyFirstComment
                                            :fatherCommentMessage="{uid: child.id,forumId:forumId,FirstCommentId:item.id}"
                                            @message-sent="handleMessage"
                                        />
                                      </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import {onMounted, ref, watch} from "vue";
import { useRouter, useRoute } from "vue-router";
import {getComments, getForumDetail, getForumLikeUser, likeForum} from "@/api/request.js";
import { addCommentApi, likeCommentApi } from "@/api/comment";
import { ElMessage } from "element-plus";
import { useCounterStore } from "@/stores/counter.js";
import ReplyFirstComment from "@/components/forumPage/forumContent/replyCommentArea/replyComment.vue";

const Router = useRouter()
const Route = useRoute()
const store = useCounterStore()
const userMessage = ref(store.UserMessage)

//获取论坛详情id
const forumId = Route.query.forumId
const commentText = ref("")

// 处理键盘按下事件的函数
const handleKeyDown = (event) => {
    // 判断是否同时按下了 Ctrl 键和 Enter 键
    if (event.ctrlKey && event.key === 'Enter') {
        // 调用发布评论的函数
        postComment();
    }
};

async function likeOrCancelThisPassage() {
  if(!sessionStorage.getItem('token')){
    ElMessage.warning('请先登录')
    await Router.push('/login')
    return
  }
  await likeForum(forumId)
  ElMessage.success('点赞成功')
}


// 为一级评论点赞
const likeFirstComment = (index) => {
  if(!sessionStorage.getItem('token')){
    ElMessage.warning('请先登录')
    Router.push('/login')
    return
  }
    const comment = comments.value[index];
    handleLikeComment(comment);
};
// 为二级评论点赞
const likeSecondComment = (index, childIndex) => {
  if(!sessionStorage.getItem('token')){
    ElMessage.warning('请先登录')
    Router.push('/login')
    return
  }
    const comment = comments.value[index].reply[childIndex];
    handleLikeComment(comment);
};
// 具体的点赞逻辑
const handleLikeComment = (comment) => {
    const commentId = comment.id;
    likeCommentApi(commentId).then(res => {
        if (comment.hasPraise === 'icon-iconfontzhizuobiaozhun023148') {
            comment.hasPraise = 'icon-dianzan';
            comment.likes++;
        } else {
            comment.hasPraise = 'icon-iconfontzhizuobiaozhun023148';
            comment.likes--;
        }
    });
};

// 发布一级评论
const postComment = () => {
    if (commentText.value.trim()) {
        // console.log('发布评论:', commentText.value);
        let comment = {
            postId: forumId,
            content: commentText.value,
            parentId: null
        }
        addCommentApi(comment).then(res => {
            ElMessage.success("发布成功")
            let comment = {
                id:res,
                user: {
                    avatar: userMessage.value.avatar,
                    username: userMessage.value.userName
                },
                createTime: '',
                content: commentText.value,
                likes: 0,
                reply: [],
                isShowReply: false,
                hasPraise: 'icon-iconfontzhizuobiaozhun023148'
            }
            comments.value.push(comment)
            content.value.commentCount++
            // 清空输入框
            commentText.value = "";
        });
    } else {
        ElMessage.warning('评论内容不能为空');
    }
};

let controlOpenFirstComment = ref(null)
// 控制一级评论回复区域显示与隐藏
function controlOpenFirstCommentArea(index) {
  controlOpenSecondComment.value = null
  if(controlOpenFirstComment.value === index) {
    controlOpenFirstComment.value = null
    return
  }
  controlOpenFirstComment.value = index
}

let controlOpenSecondComment=ref(null)
// 控制二级评论回复区域显示与隐藏
function replySecondComment(childId){
  controlOpenFirstComment.value = null
  if(controlOpenSecondComment.value === childId) {
    controlOpenSecondComment.value = null
    return
  }
  controlOpenSecondComment.value = childId
}


let ifChangeCommentList=ref(null)
watch(ifChangeCommentList,() => {
  if (ifChangeCommentList.value !== null) {
    getForumDetails(ifChangeCommentList.value)
    ifChangeCommentList.value = null
  }
})
// 子组件发送消息给父组件
function handleMessage(message) {
  ifChangeCommentList.value = message
}



//获取论坛详情数据
let content = ref({
    avatar: '',
    username: '',
    createTime: '',
    title: '',
    content: '',
    commentCount: 0,
    praise: 0,
  hasPraised: 'icon-iconfontzhizuobiaozhun023148'
})

//获取评论数据
let comments = ref(null)

//初始化评论数据
function InitComments() {
  comments.value=[{
    user: {
      picture: '',
      username: ''
    },
    createTime: '',
    content: '',
    likes: 0,
    reply: [{
      user: {
        name: '',
        picture: ''
      },
      createTime: '',
      content: '',
      likes: 0
    }]
  }]
}
InitComments()

//获取论坛详情数据和评论数据
async function getForumDetails(id) {
    content.value = await getForumDetail(forumId)
    if(sessionStorage.getItem('token')){
      let HasPraised = await getForumLikeUser(forumId)
      if(HasPraised.indexOf(userMessage.value.id) !== -1) {
        content.value.hasPraised = 'icon-dianzan'
      }else {
        content.value.hasPraised = 'icon-iconfontzhizuobiaozhun023148'
      }
    }
    let data = await getComments(forumId)
    InitComments()
    comments.value = data.commentList
    let userHasPraised = data.likeIds
    // 遍历一级评论
    for (let i = 0; i < comments.value.length; i++) {
      if(comments.value[i].id===id){
        comments.value[i].isShowReply= true
        comments.value[i].ControlReply = 'icon-icon_function_shouqi'
      }else {
        comments.value[i].isShowReply = false
        comments.value[i].ControlReply = 'icon-fangxia'
      }
        // 判断用户是否为当前一级评论点过赞
        if (userHasPraised.indexOf(comments.value[i].id) !== -1) {
            comments.value[i].hasPraise = 'icon-dianzan'
        } else {
            comments.value[i].hasPraise = 'icon-iconfontzhizuobiaozhun023148'
        }
        // 遍历二级评论
        for (let k = 0; k < comments.value[i].reply.length; k++) {
            let tm = comments.value[i].reply[k]
            let tmId = tm.id
            if (userHasPraised.indexOf(tmId) !== -1) {
                tm.hasPraise = 'icon-dianzan'
            } else {
                tm.hasPraise = 'icon-iconfontzhizuobiaozhun023148'
            }
        }
    }
    // console.log(comments.value)
}
getForumDetails()

// 点赞或取消点赞本帖子
async function likeOrCancelLike() {
  if (!sessionStorage.getItem('token')) {
    ElMessage.warning("请先登录")
    return
  }
  await likeForum(forumId)
  if (content.value.hasPraised === 'icon-iconfontzhizuobiaozhun023148') {
    content.value.hasPraised = 'icon-dianzan'
    content.value.praise++
    ElMessage.success("点赞成功")
  }else {
    content.value.hasPraised = 'icon-iconfontzhizuobiaozhun023148'
    content.value.praise--
    ElMessage.success("取消点赞成功")
  }
}


function backPage() {
    Router.back()
}

// 控制回复区域显示与隐藏
function ShowReplyArea(index) {
    let show = comments.value[index].isShowReply
    if (show === false) {
        comments.value[index].ControlReply = "icon-icon_function_shouqi"
        comments.value[index].isShowReply = true
    } else {
        comments.value[index].ControlReply = "icon-fangxia"
        comments.value[index].isShowReply = false
    }
}

</script>